package ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DialogImpl implements Dialog
{
	private PrintStream out = System.out;
	private BufferedReader in = 
		new BufferedReader(new InputStreamReader(System.in));
	
	private List commands;
	
	private String version;
	
	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public List getCommands()
	{
		return commands;
	}

	public void setCommands(List commands)
	{
		this.commands = commands;
	}

	public Command chooseCommand()
	{
		return (Command) selectChoice("", commands);
	}

	private Choice selectChoice(String question, List choices)
	{
		out.print(question);
		Map<String, Choice> choiceMap = new HashMap<String, Choice>();
		boolean isFirst = true;
		for (Iterator it = choices.iterator(); it.hasNext();)
		{
			Choice choice = (Choice) it.next();
			if (!isFirst)
				out.print(", ");
			isFirst = false;
			
			out.print(choice.getDescription());
			choiceMap.put(choice.getAbbreviation().toUpperCase(), choice);
		}
		out.print("? ");
		String abbreviation = readLine().toUpperCase();
		Choice choice = choiceMap.get(abbreviation);
		if (choice == null)
			throw new IllegalArgumentException("Invalid choice.");
		
		return choice;
	}
	
	private String readLine()
	{
		try
		{
			return in.readLine();
		} catch (IOException e)
		{
			throw new RuntimeException("Failed to read user input.", e);
		}
	}

	/* (non-Javadoc)
	 * @see ui.Dialogx#display(java.lang.String)
	 */
	public void display(String message)
	{
		out.println(message);
	}

	public void displayVersion() {
		display("NEAT Snapper v" + version);
	}
	
	/* (non-Javadoc)
	 * @see ui.Dialogx#ask(java.lang.String)
	 */
	public String ask(String question)
	{
		display(question);
		return readLine();
	}

	public Date askDate(String question) throws ParseException
	{
		DateFormat format = new SimpleDateFormat("dd MMM yyyy");
		return format.parse(ask(question));
	}

	public String ask(String question, String defaultAnswer)
	{
		String answer = ask(question + "[" + defaultAnswer + "] ");
		return answer.length() > 0 ? answer : defaultAnswer;
	}
}
